package com.atguigu.blockingqueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: BlockingQueueDemo
 * Package: com.atguigu.blockingqueue
 * Description:
 *
 * @author: fu-wang
 * @create: 2024/10/29 21:12
 * version: 1.0
 */
public class BlockingQueueDemo {
    public static void main(String[] args) throws InterruptedException {
        //创建有界阻塞队列（先进先出原则）
        ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<>(3);
        /**
         //抛异常
         System.out.println(queue.add("a"));
         System.out.println(queue.add("b"));
         System.out.println(queue.add("c"));
         //System.out.println(queue.add("d"));//IllegalStateException
         System.out.println(queue.element());//a 队首
         System.out.println(queue.remove());
         System.out.println(queue.remove());
         System.out.println(queue.remove());
         //System.out.println(queue.remove());//NoSuchElementException */

        /**
        //特殊值
        System.out.println(queue.offer("a"));
        System.out.println(queue.offer("b"));
        System.out.println(queue.offer("c"));
        //System.out.println(queue.offer("d"));//false
        System.out.println(queue.peek());
        System.out.println(queue.peek());
        System.out.println(queue.peek());//a 队首
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        //System.out.println(queue.poll());//null */

        /**
        //阻塞
        queue.put("a");
        queue.put("b");
        queue.put("c");
//        queue.put("d");//队列满，发生阻塞
        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.take());
//        System.out.println(queue.take());//队列已空，发生阻塞 */

        //超时
        System.out.println(queue.offer("a"));
        System.out.println(queue.offer("b"));
        System.out.println(queue.offer("c"));
        System.out.println(queue.offer("d",5, TimeUnit.SECONDS));//队列已满，加入队列超时 返回false
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());//队列已空，取值为null
    }
}
